//
//  GroupSearchRecordVC.m
//  Bees
//
//  Created by NowYouCanSee on 2019/3/13.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "GroupSearchRecordVC.h"
#import "NTESSearchLocalHistoryObject.h"
#import "NTESBundleSetting.h"
#import "NTESSearchMessageContentCell.h"
#import "NTESSessionHistoryViewController.h"
#define ContentCellIdentity  @"content"
#define ContentCellHeight    50

#define SearchLimit  10

@interface GroupSearchRecordVC ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *searchTF;
@property (nonatomic,strong) NTESSearchLocalHistoryObject *searchObject;
@property (nonatomic,strong)  NIMSession *session;
@property (nonatomic,strong) UILabel *noResultTip;
@property (nonatomic,strong) NSArray *members;
@property (nonatomic,copy)   NSString *keyWord;

@property (nonatomic,strong) NSMutableArray *data;
@property (nonatomic,strong) NIMMessageSearchOption *lastOption;
@end

@implementation GroupSearchRecordVC
- (instancetype)initWithSession:(NIMSession *)session{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _session = session;
        NTESSearchLocalHistoryObject *object = [[NTESSearchLocalHistoryObject alloc] init];
        _searchObject = object;
        _data = [[NSMutableArray alloc]init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self prepareMember];
}
- (void)prepareMember{
    if (self.session.sessionType == NIMSessionTypeTeam) {
        __weak typeof(self) wself = self;
        [[NIMSDK sharedSDK].teamManager fetchTeamMembers:self.session.sessionId completion:^(NSError *error, NSArray *members) {
            NSMutableArray *data = [[NSMutableArray alloc] init];
            for (NIMTeamMember *member in members) {
                if(member.userId.length){
                    [data addObject:member.userId];
                }
            }
            wself.members = data;
        }];
    }else{
        NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
        self.members = @[self.session.sessionId,me];
    }
}
///开始搜索
- (void)beginSearch{
    self.keyWord = self.searchTF.text;
    if (!self.keyWord.length) {
        [self.view makeToast:XLocalized(@"请输入您要搜索的内容")];
        return;
    }
    [self.data removeAllObjects];
    NIMMessageSearchOption *option = [[NIMMessageSearchOption alloc] init];
    option.searchContent = self.keyWord;
    NSArray *uids = [self searchUsersByKeyword:self.keyWord users:self.members];
    option.fromIds       = uids;
    option.limit         = SearchLimit;
    option.order         = [NTESBundleSetting sharedConfig].localSearchOrderByTimeDesc? NIMMessageSearchOrderDesc: NIMMessageSearchOrderAsc;
    option.allMessageTypes = YES;
    self.lastOption      = option;
    [self showSearchData:option loadMore:YES];
}
///UIUI
- (void)setupUI{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-70, 44)];
    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(titleView.width-35, 4.5, 35, 35)];
    [searchBtn setImage:IMAGE_NAMED(@"search") forState:UIControlStateNormal];
    [titleView addSubview:searchBtn];
    UIView*line = [[UIView alloc]initWithFrame:CGRectMake(0, titleView.height-CGFloatFromPixel(1.0f), titleView.width, CGFloatFromPixel(1.0f))];
    line.backgroundColor = UIColorHex(#FFCC03);
    [titleView addSubview:line];
    [searchBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [self beginSearch];
    }];
    self.searchTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, titleView.width-searchBtn.width, titleView.height-line.height)];
    self.searchTF.delegate = self;
    [titleView addSubview:self.searchTF];
    self.searchTF.placeholder = XLocalized(@"搜索聊天记录");
    self.searchTF.returnKeyType = UIReturnKeySearch;
    self.navigationItem.titleView = titleView;
    [self.tableView registerClass:[NTESSearchMessageContentCell class] forCellReuseIdentifier:ContentCellIdentity];
    self.tableView.tableFooterView = [UIView new];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NTESSearchLocalHistoryObject *object = self.data[indexPath.row];
    UITableViewCell<NTESSearchObjectRefresh> *cell = [tableView dequeueReusableCellWithIdentifier:ContentCellIdentity];
    [cell refresh:object];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NTESSearchLocalHistoryObject *object = self.data[indexPath.row];
    return object.uiHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NTESSearchLocalHistoryObject *object = self.data[indexPath.row];
    NTESSessionHistoryViewController *sessionVC = [[NTESSessionHistoryViewController alloc] initWithSession:self.session andSearchMsg:object.message];
    [self.navigationController pushViewController:sessionVC animated:YES];
}
#pragma mark - Action
- (void)loadMore:(BOOL)isMore{
    if (!isMore) {
        if (!self.keyWord.length) {
            NTESSearchLocalHistoryObject *obj  = self.data.firstObject;
            if ([NTESBundleSetting sharedConfig].localSearchOrderByTimeDesc == NIMMessageSearchOrderDesc) {
                self.lastOption.startTime      = 0;
                self.lastOption.endTime        = obj.message.timestamp;
            }else{
                self.lastOption.startTime      = obj.message.timestamp;
                self.lastOption.endTime        = 0;
            }
            [self showSearchData:self.lastOption loadMore:NO];
        }
    }else{
        if (!self.keyWord.length) {
            NTESSearchLocalHistoryObject *obj  = self.data.lastObject;
            if ([NTESBundleSetting sharedConfig].localSearchOrderByTimeDesc == NIMMessageSearchOrderDesc) {
                self.lastOption.startTime      = obj.message.timestamp;
                self.lastOption.endTime        = 0;
            }else{
                self.lastOption.startTime      = 0;
                self.lastOption.endTime        = obj.message.timestamp;
            }
            [self showSearchData:self.lastOption loadMore:YES];
        }
    }
    [self endHeaderFooterRefreshing];
}

#pragma mark - Private

- (void)showSearchData:(NIMMessageSearchOption *)option loadMore:(BOOL)loadMore{
    __weak typeof(self) wself = self;
    [[NIMSDK sharedSDK].conversationManager searchMessages:self.session option:option result:^(NSError *error, NSArray *messages) {
        messages = [NTESBundleSetting sharedConfig].localSearchOrderByTimeDesc == NIMMessageSearchOrderAsc ? messages.reverseObjectEnumerator.allObjects : messages;
        NSMutableArray *array = [[NSMutableArray alloc]init];
        for (NIMMessage *message in messages) {
            NTESSearchLocalHistoryObject *obj = [[NTESSearchLocalHistoryObject alloc] initWithMessage:message];
            obj.type     = SearchLocalHistoryTypeContent;
            [array addObject:obj];
        }
        if (loadMore) {
            [wself.data addObjectsFromArray:array];
            wself.tableView.mj_footer.hidden = array.count == SearchLimit? NO : YES;
            wself.noResultTip.hidden = wself.data.count != 0;
        }else{
            [array addObjectsFromArray:self.data];
            wself.data = array;
        }
        wself.keyWord = nil;
        [wself.tableView reloadData];
    }];
}

- (NSArray *)searchUsersByKeyword:(NSString *)keyword users:(NSArray *)users{
    NSMutableArray *data = [[NSMutableArray alloc] init];
    for (NSString *uid in users) {
        NIMKitInfo *info = [[NIMKit sharedKit] infoByUser:uid option:nil];
        [data addObject:info];
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF.showName CONTAINS[cd] %@",keyword];
    NSArray *array = [data filteredArrayUsingPredicate:predicate];
    NSMutableArray *output = [[NSMutableArray alloc] init];
    for (NIMKitInfo *info in array) {
        [output addObject:info.infoId];
    }
    return output;
}
#pragma mark extField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self beginSearch];
    return YES;
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"无结果!";
    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:14.0f],
                                 NSForegroundColorAttributeName:[UIColor lightGrayColor],
                                 NSParagraphStyleAttributeName:paragraph
                                 };
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
